<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;
use app\model\Customer;
use app\model\Principal;

class SemData extends Common
{

	/**
	 * 请求类型
	 *
	 * @return
	 */
	public function method(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semdata:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		if($sort == 'ipAddr'){
			$sort = 'ip';
		}

		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['userType', '=', 1 ] );

		$username = $request->param('username', '', 'trim');
		if($username) {
			array_push( $where, ['userid', '=',  $username ] );
		}

		$customerid = $request->param('customerid', '', 'trim');
		if($customerid) {
			array_push( $where, ['customerid', '=',  $customerid ] );
		}

		$contact = $request->param('contact', '', 'trim');
		if($contact) {
			array_push( $where, ['contact', '=',  $contact ] );
		}
		
		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['bazaarId', '=',  $bazaarId ] );
		}

		$accessPage = $request->param('accessPage', '', 'trim');
		if($accessPage) {
			array_push( $where, ['accessPage', '=',  $accessPage ] );
		}

		$ocpcType = $request->param('ocpcType', '', 'trim');
		if($ocpcType) {
			array_push( $where, ['ocpcType', '=',  $ocpcType ] );
		}

		$ocpcStatus = $request->param('ocpcStatus', '', 'trim');
		if($ocpcStatus) {
			array_push( $where, ['ocpcStatus', '=',  $ocpcStatus ] );
		}

		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			array_push( $where, ['copyTime', 'between', cloud_datetime_format( $createTimeStart, $createTimeEnd, false) ] );
		} else {
			array_push( $where, ['copyTime', 'between', [ date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")) ] ] );
		}
       $roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('semauthaccount');
			if($authaccount) {
				array_push( $where, ['userid', 'in',  $authaccount ] );
			}
		}
		$query = Db::name('cfg_copy')->where($where)->order($sort, $order)->paginate($limit);
		$items = $query->items();
		$address = new \Net\IpLocation( app()->getRootPath() . 'data' . DIRECTORY_SEPARATOR . 'qqwry.dat');
		$serviceArray = Db::table('cfg_service')->field('name,nickname,wechat')->where('companyId', $request->sessInfo['companyId'])->select()->toArray();
		foreach ( $items as &$value ) {
			if( empty($value['wechatNickname']) ) {
				$value['wechatName'] = cloud_get_array_value($serviceArray, $value['wechat'], 'wechat', 'name', null);
				$value['wechatNickname'] = cloud_get_array_value($serviceArray, $value['wechat'], 'wechat', 'nickname', null);
			}
			$value['addr'] = $address->getAddrName($value['ip']);
		}

		unset($value);
		return ['code'=> 0, 'msg'=> '', 'count'=> $query->total(), 'data'=> $items,
			'expand' => Expand::getList($request->sessInfo, 1),
		  'customer' => Customer::getList($request->sessInfo),
		  'principal' => Principal::getList($request->sessInfo),
			'bazaar' => Bazaar::getList($request->sessInfo, 1) ];
	}

	/**
	 * 设置OCPC回传方式
	 *
	 * @return
	 */
	public function ocpcType(Request $request, $id)
	{
		if($this->hasPermission($request->sessInfo, 'semdata:ocpctype')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$type = $request->param('type', '', 'trim');
		if(empty($type)) {
			return ['code'=>403, 'msg'=>'回传方式不能为空!'];
		}
		$where = [];
		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['ocpcType', '<>', $type ] );
		array_push( $where, ['ocpcStatus', '=', 1 ] );
		array_push( $where, ['userType', '=', 1 ] );
		array_push( $where, ['id', 'in', $id ] );
		$count = Db::table('cfg_copy')->where($where)->count();
		Db::name('cfg_copy')->where($where)->update(['ocpcType' => $type]);
		//echo Db::getLastSql();
		return ['code'=> 0, 'msg'=> '成功修改'.$count.'条数据!'];
	}

	/**
	 * OCPC回传
	 *
	 * @return
	 */
	public function uploadConvertData($token, $logidUrl, $convertType) {
		$reqData = json_encode(['token' => $token, 'conversionTypes' => [[ 'logidUrl' => $logidUrl, 'convertType' => $convertType ]]]);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_URL, 'https://ocpc.baidu.com/ocpcapi/api/uploadConvertData');
		curl_setopt($ch, CURLOPT_POSTFIELDS, $reqData);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false );
		curl_setopt($ch, CURLOPT_HTTPHEADER, array (
			'Content-Type: application/json; charset=utf-8',
			'Content-Length: ' . strlen($reqData)
			)
		);
		for ($i = 0; $i < 5; $i++) {
			$response = curl_exec($ch);
			$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if ($httpcode === 200) {
				$data = json_decode($response, true);
				$status = $data['header']['status'];
				if ( $status !== 4 ) {
					curl_close($ch);
					return $status === 0;
				}
			}
		}
		curl_close($ch);
		return false;
	}

	/**
	 * 开始回传OCPC
	 *
	 * @return
	 */
	public function ocpc(Request $request, $id)
	{
		if($this->hasPermission($request->sessInfo, 'semdata:ocpc')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}

		$query = Db::table('cfg_copy')->where('companyId', $request->sessInfo['companyId'])->where('id', $id)->find();
		if(!isset($query['id'])){
			return ['code'=> 403, 'msg'=> '数据不存在, 回传失败!'];
		}

		if(empty($query['ocpcCode'])) {
			return ['code'=> 403, 'msg'=> '转换类型未设置, 回传失败!'];
		}

		if(empty($query['vid'])){
			return ['code'=> 403, 'msg'=> '未检测到VID, 回传失败!'];
		}

		$token = Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])->where('userid', $query['userid'])->value('ocpc');
		if(empty($token)) {
			return ['code'=>403, 'msg'=>'OCPC未设置, 回传失败!'];
		}

		$ocpclog = Db::table('cfg_ocpclog')->where('url', $query['url'])->value('id');
		if($ocpclog) {
      Db::name('cfg_copy')->where('id', $query['id'])->update(['ocpcStatus' => 4, 'ocpcTime' => date('Y-m-d H:i:s')]);
			return ['code'=>403, 'msg'=>'其他时段已回传, 回传失败!'];
		}

		$convertData = $this->uploadConvertData($token, $query['url'], $query['ocpcCode']);
		if($convertData) {
			Db::name('cfg_ocpclog')->insert(['url' => $query['url'], 'datatime' => date('Y-m-d H:i:s')]);
			Db::name('cfg_copy')->where('id', $query['id'])->update(['ocpcStatus' => 5, 'ocpcTime' => date('Y-m-d H:i:s')]);
			return ['code'=> 0, 'msg'=> '回传成功!', 'ocpcStatus'=> 5];
		}

		return ['code'=> 0, 'msg'=> 'URL数据异常, 回传失败!'];
	}

	/**
	 * 批量OCPC回传
	 *
	 * @return
	 */
	public function ocpcBatch(Request $request, $id)
	{
		if($this->hasPermission($request->sessInfo, 'semdata:ocpc')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$where = [];
		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['ocpcStatus', '=', 1 ] );
		array_push( $where, ['id', 'in', $id ] );
		$query = Db::table('cfg_copy')->where($where)->select()->toArray();
		$number = count($query);
		if($number == 0) {
			return ['code'=> 403, 'msg'=> '数据不存在, 回传失败!'];
		}
		$succeed = 0;
		foreach( $query as $value ) {
			if( $value['vid'] && $value['ocpcCode']) {
				$token = Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])->where('userid', $value['userid'])->value('ocpc');
				if($token) {
					$ocpclog = Db::table('cfg_ocpclog')->where('url', $value['url'])->value('id');
					if(empty($ocpclog)) {
						$convertData = $this->uploadConvertData($token, $value['url'], $value['ocpcCode']);
						if($convertData) {
							$succeed++;
							Db::name('cfg_ocpclog')->insert(['url' => $value['url'], 'datatime' => date('Y-m-d H:i:s')]);
							Db::name('cfg_copy')->where('id', $value['id'])->update(['ocpcStatus' => 5, 'ocpcTime' => date('Y-m-d H:i:s')]);
						}
					}
				}
			}
		}
		return ['code'=> 0, 'msg'=> '成功回传'.$succeed.'条数据!'];
	}
}
